Function methods
Implementations that encapsulate multiple lines of code via white/black boxes, generally having input and output, are used to simplify code, repeat calls and modularize programming.
Functions can be defined in Python using the def
keyword, and like variables each function has a ringing name, and the naming rules are the same as those for variables. When the first statement within a function is a string, that string is a document string, also known as a docstring.
def fib(n):
"""Outputs a Fibonacci series function within a bounded value."""
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
``''
### Default-valued arguments
In Python, functions can have default values for their arguments and also support the use of mutable arguments, so Python doesn't need to support function overloading as much as other languages do, since we can make a function available in a number of different ways when we define it.
```python
def add(a=0, b=0, c=0):
"""Add three numbers together""""
return a + b + c
add(1,2)
# 3
Key-value arguments
Keyword arguments of the form kwarg=value
can also be used to call functions. An example function is as follows.
This function takes one mandatory argument (voltage
) and three optional arguments (state
, action
and type
).
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")
parrot("halo",type="test")
# -- This parrot wouldn't voom if you put halo volts through it.
# -- Lovely plumage, the test
# -- It's a stiff !
Special parameters
Variable arguments *
A * in front of an argument name indicates that args is a variable argument, and multiple arguments can be entered.
def add2(*args):
total = 0
for val in args:
total += val
print(total)
add2(1,2,3)
# 6
key-value arguments **
A ** in front of an argument name indicates that args is a variable argument that can be entered as a key-value pair.
def add2(**arg):
print(arg)
add2(name="halo")
# {'name': 'halo'}
limited position arguments /
`/
must be placed after the formal parameter to indicate a restricted position argument, and the real parameter must be entered at the position of the formal parameter.
def pos_only_arg(arg, /):
print(arg)
limited keyword arguments *
`*
must be placed before the form parameter to indicate a keyword-limited argument, and the real parameter must be entered as a key-valued argument.
def kwd_only_arg(*, arg):
print(arg)
Special argument combinations
def combined_example(pos_only, /, standard, *, kwd_only):
print(pos_only, standard, kwd_only)
"""
Example run
"""
>>> combined_example(1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: combined_example() takes 2 positional arguments but 3 were given
>>> combined_example(1, 2, kwd_only=3)
1 2 3
>>>> combined_example(1, standard=2, kwd_only=3)
1 2 3
>>>> combined_example(pos_only=1, standard=2, kwd_only=3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: combined_example() got some positional-only arguments passed as keyword arguments: 'pos_only'
Lambda expressions
The lambda keyword is used to create small anonymous functions. lambda a, b: The a+b function returns the sum of two arguments. lambda functions can be used anywhere a function object is needed. Syntactically, an anonymous function can only be a single expression. Semantically, it is just syntactic sugar for the regular function definition. As with nested function definitions, lambda functions can refer to variables in the containing scope: the
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>>> f(0)
42
>>>> f(1)
43